package com.x.mvp.widget;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.x.mvp.R;
import com.x.mvp.utils.MediaUtil;

import java.io.File;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

public class GetImageDialog extends DialogFragment {
    //    private static final int SELECT_PIC_BY_TACK_PHOTO = 1001;
//    private static final int SELECT_PIC_BY_PICK_PHOTO = 1002;
    private static final int TACK_PHOTO = 1003;
    private static final int PICK_PHOTO = 1004;
    private static final String PHOTO_PATH = "avatar.jpg";
    private static final String PHOTO_CAMRA_PATH = "avatar_camra.jpg";
    private static final String MIME_TYPE_IMAGE = "image/*";

    private Uri originalUri;
    private OnImageUrlListener onImageUrlListener;
    private LinearLayout mPopupAvatarCamera;
    private LinearLayout mPopupAvatarPhotos;
    private View cannel;
    ProgressBar mPopupAvatarPhotosProgress;
    ProgressBar mPopupAvatarCamerProgress;
    File mTmpFile;
    File mTmpCamraFile;
    File getmTmpFile() {
        long s = System.currentTimeMillis();
        if(mTmpFile == null) {
            mTmpFile = new File(Environment.getExternalStorageDirectory(), s + PHOTO_PATH);
        }
        return mTmpFile;
    }

    File getmTmpCamraFile() {
        long s = System.currentTimeMillis();
        if(mTmpCamraFile == null) {
            mTmpCamraFile = new File(Environment.getExternalStorageDirectory(), s + PHOTO_CAMRA_PATH);
        }
        return mTmpCamraFile;
    }

    public interface OnImageUrlListener {
        public void onImageUrl(String url, String local);
    }

    public void setOnImageUrlListener(OnImageUrlListener onImageUrlListener) {
        this.onImageUrlListener = onImageUrlListener;
    }

    protected CompositeSubscription subscriptions = new CompositeSubscription();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.popup_pic_selection, container, false);
        //设置标题
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        mPopupAvatarCamera = (LinearLayout) v.findViewById(R.id.popup_avatar_camera);
        mPopupAvatarPhotos = (LinearLayout) v.findViewById(R.id.popup_avatar_photos);
        mPopupAvatarPhotosProgress = (ProgressBar) v.findViewById(R.id.popup_avatar_photos_progress);
        mPopupAvatarCamerProgress = (ProgressBar) v.findViewById(R.id.popup_avatar_camera_progress);
        cannel = v.findViewById(R.id.cannel);
        setOnClick();
        return v;
    }

    public void setOnClick() {
        mPopupAvatarCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });
        mPopupAvatarPhotos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickPhoto();
            }
        });
        cannel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

    }


    public void addSubscription(Subscription subscription) {
        subscriptions.add(subscription);
    }

    public void unsubscribe() {
        subscriptions.unsubscribe();
    }


    @Override
    public void onDestroyView() {
        unsubscribe();
        super.onDestroyView();
    }

    private void takePhoto() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getmTmpCamraFile()));
            startActivityForResult(intent, TACK_PHOTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void pickPhoto() {
        Intent mIntent = new Intent(Intent.ACTION_PICK);
        mIntent.setType(MIME_TYPE_IMAGE);

        startActivityForResult(mIntent, PICK_PHOTO);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
//                case SELECT_PIC_BY_PICK_PHOTO:
//                    originalUri = data.getData();
//                    cropImageUri(originalUri, 425, 270, PICK_PHOTO);
//                    break;
//                case SELECT_PIC_BY_TACK_PHOTO:
//                    Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + PHOTO_CAMRA_PATH);
//                    if (MediaUtil.saveBitmap(mTmpCamraFile, bitmap, Bitmap.CompressFormat.JPEG)) {
//                        originalUri = Uri.fromFile(mTmpCamraFile);
//                        cropImageUri(originalUri, 425, 270, TACK_PHOTO);
//                    } else {
//                        Toast.makeText(this.getContext(), R.string.msg_image_compress_error, Toast.LENGTH_LONG).show();
//                    }
//                    break;
                case PICK_PHOTO:
                    originalUri = data.getData();
                    uploadImage(requestCode, originalUri);
                    break;
                case TACK_PHOTO:
                    upDateImage(getmTmpCamraFile().getPath());
                    break;
                default:
                    break;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void uploadImage(int requestCode, Uri uri) {
        if (uri != null) {
            if (PICK_PHOTO == requestCode) {
                mPopupAvatarPhotosProgress.setVisibility(View.VISIBLE);
            } else {
                mPopupAvatarCamerProgress.setVisibility(View.VISIBLE);
            }
            String path = MediaUtil.getPath(this.getContext(), uri);
            upDateImage(path);
        }
    }

    public void upDateImage(String path) {
        mPopupAvatarPhotosProgress.setVisibility(View.GONE);
        mPopupAvatarCamerProgress.setVisibility(View.GONE);
        if (onImageUrlListener != null) {
            onImageUrlListener.onImageUrl(path, path);
        }
        dismissAllowingStateLoss();
    }

    public void show(FragmentManager ft) {
//        FragmentTransaction ft = getChildFragmentManager().beginTransaction();
//        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        show(ft, "df");
    }


    public void toast(int resId) {
        toast(resId, Toast.LENGTH_SHORT);
    }

    public void toast(int resId, int length) {
        Toast.makeText(getActivity(), getString(resId), length).show();
    }

    public void toast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Uri outputUri = Uri.fromFile(getmTmpFile());
        Intent intent = new Intent("com.android.camera.action.CROP");
        //对图片uri进行一次转化因为如果是4.4以上的版本不能直接根据返回的uri进行图片裁剪
        String uriString = getPath(this.getContext(), uri);
        Uri newUri = Uri.fromFile(new File(uriString));
        intent.setDataAndType(newUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    @Nullable
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
